package com.hd.controller.upload;

import com.hd.controller.base.BaseController;
import com.hd.util.JsonUtil;
import com.hd.util.QiniuUtil;
import com.hd.util.id.AttachIdGenerator;
import com.hd.util.id.IdGenerator;
import com.qiniu.http.Response;
import com.qiniu.storage.model.DefaultPutRet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

/**
 * 七牛云上传下载文件
 */
@Controller
@RequestMapping("/qiniu")
public class QiniuUploadController extends BaseController{
    private static final Logger log= LoggerFactory.getLogger(QiniuUploadController.class);
    @ResponseBody
    @RequestMapping("/upload")
    public Object upload(@RequestParam("file")MultipartFile file){
        log.info("[文件类型] - [{}]", file.getContentType());
        log.info("[文件名称] - [{}]", file.getOriginalFilename());
        log.info("[文件大小] - [{}]", file.getSize());
        try {
            QiniuUtil qiniuUtil = new QiniuUtil();
            String newfileName = AttachIdGenerator.generator() + getType(file.getOriginalFilename());
            Response response = qiniuUtil.upload2(file.getBytes(), newfileName);
            DefaultPutRet set = JsonUtil.parse(response.bodyString(), DefaultPutRet.class);
            String url = qiniuUtil.defaultTargetURL + "/" + newfileName;
            return renderSuccess("上传成功",url);
        }catch (IOException e){
            return renderSuccess("上传出错了");
        }
    }

    /**
     * 获取文件类型
     * @param fileName
     * @return
     */
    private String getType(String fileName){
        return fileName.substring(fileName.lastIndexOf("."),fileName.length());
    }

}
